package com.xyz.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import com.xyz.constant.XYZConstant;

/**
 * @author xyzjh
 * 
 */
public class SEQNoHelper {
	/**
	 * @param flag
	 * @return
	 */
	public static String getSeqNo(String flag) {

		StringBuilder stringBuffer = new StringBuilder(32);
		stringBuffer.append(flag);
		stringBuffer.append(getNowDate());
		stringBuffer.append(getRandom(4)); //javascript对于太长的id会导致精度丢失
		return stringBuffer.toString();

	}

	public static String getNowDate() {
		Date date = new Date();
		SimpleDateFormat simFormat = new SimpleDateFormat(
				XYZConstant.MMDDHHMMSS);
		return simFormat.format(date);
	}

	public static String getRandom(int n) {
		if (n < 1 || n > 10) {
			throw new IllegalArgumentException("cannot random " + n
					+ " bit number");
		}
		Random ran = new Random();
		if (n == 1) {
			return String.valueOf(ran.nextInt(10));
		}
		int bitField = 0;
		char[] chs = new char[n];
		for (int i = 0; i < n; i++) {
			while (true) {
				int k = ran.nextInt(10);
				if ((bitField & (1 << k)) == 0) {
					bitField |= 1 << k;
					chs[i] = (char) (k + '0');
					break;
				}
			}
		}
		return new String(chs);
	}

	public static void main(String[] args) {
		System.out.println(getSeqNo("11"));
	}
}
